package fetch.paginegialle;

import java.io.*;
import java.util.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import utils.string.StringCleaner;

import data.Business;

public class ParserXml2Biz {
	
	public String city;
	public String state;
	
	public ParserXml2Biz(String city, String state) {
		this.city = city;
		this.state = state;
	}
		
	public static final String xpath_name = "response/results/result/name";
	public static final String xpath_address = "response/results/result/address";
	public static final String xpath_category = "response/results/result/category";
	public static final String xpath_latitude = "response/results/result/latitude";
	public static final String xpath_logitude = "response/results/result/longitude";
	
	public void xml2biz(File xml, Set<Business> biz) {
		try {
			InputSource docIS = new InputSource(new FileReader(xml));
			Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(docIS);
			NodeList n = process(doc,xpath_name);
			NodeList a = process(doc,xpath_address);
			NodeList c = process(doc,xpath_category);
			NodeList lat = process(doc,xpath_latitude);
			NodeList lon = process(doc,xpath_logitude);
			
			
			for(int i=0; i<n.getLength();i++) {
				String name = StringCleaner.clean(n.item(i).getTextContent());
				String address = StringCleaner.clean(a.item(i).getTextContent());
				String category = StringCleaner.clean(c.item(i).getTextContent());
				double latitude = Double.parseDouble(lat.item(i).getTextContent());
				double longitude = Double.parseDouble(lon.item(i).getTextContent());
				Business b = new Business(name,address,city,state,category,latitude,longitude);
				biz.add(b);
			}
		}catch(Exception e) {
			System.err.println(xml.getName());
			e.printStackTrace();
		}
	}

	
	
	private NodeList process(Document doc, String xpath) {
		XPathFactory factory = XPathFactory.newInstance();
		NodeList result = null;
		
		XPath xp = factory.newXPath();
		try {
			result = (NodeList)xp.evaluate(xpath, doc, XPathConstants.NODESET);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return result;
	}
	
}
